<template>
  <a-drawer
    :title="title"
    :visible="visible"
    :width="600"
    :body-style="{
      paddingBottom: '60px',
      height: 'calc(100% - 65px)',
    }"
    @close="onClose"
  >
    <div class="content">
      <template v-if="showTemplateList">
        <a-table
          :dataSource="templateList"
          :columns="columns"
          :pagination="false"
          rowKey="id"
          bordered
          size="small"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'name'">
              <a-tooltip v-if="record.name.length > 8">
                <template #title>{{ record.name }}</template>
                <div>{{ record.name.slice(0, 8) }}...</div>
              </a-tooltip>
              <div v-else>{{ record.name }}</div>
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                type="link"
                @click="editTemplate(record.id)"
                style="padding: 0 5px; margin: 0; font-size: 12px"
                >编辑</a-button
              >
              <a-button
                type="link"
                danger
                @click="deleteTemplate(record.id)"
                style="padding: 0 5px; margin: 0; font-size: 12px"
                >删除</a-button
              >
            </template>
          </template>
        </a-table>
      </template>
      <template v-else>
        <a-row>
          <div style="display: flex; align-items: center">
            <span style="color: red">*</span>模板名称:
          </div>
          <a-input
            v-model:value="editTemplateName"
            style="width: 400px; margin-left: 10px"
          />
        </a-row>
        <div class="edit-table mt-20">
          <div class="edit-table-head">
            <div class="edit-table-part" style="border-right: 1px solid #fff">
              <div class="edit-table-partChild">
                <div class="edit-table-partCore">系统项</div>
              </div>
              <div class="edit-table-partChild">Excel对应列</div>
            </div>
          </div>
          <div class="edit-table-body">
            <div
              class="edit-table-part"
              v-for="(item, index) of editTemplateTable"
              :key="index"
            >
              <div class="edit-table-partChild">
                <div class="edit-table-partCore">
                  <span style="color: red" v-if="item.checked">*</span>
                  {{ item.name }}
                </div>
              </div>
              <div class="edit-table-partChild">
                <a-select
                  v-model:value="item.row"
                  style="width: 180px; margin-left: 22px"
                  :options="item.key == 'match_line' ? rowList : lettersList"
                  mode="multiple"
                  :maxTagCount="3"
                  @change="onSelectChange"
                  placeholder="请选择对应列"
                  allowClear
                  v-if="item.key == 'voucher_no'"
                >
                </a-select>
                <a-select
                  v-model:value="item.row"
                  style="width: 180px"
                  :options="item.key == 'match_line' ? rowList : lettersList"
                  @change="onSelectChange"
                  :placeholder="
                    item.key == 'match_line' ? '请选择起始行' : '请选择对应列'
                  "
                  allowClear
                  v-else
                  :style="{
                    marginLeft: item.key == 'match_line' ? ' ' : '',
                  }"
                >
                </a-select>

                <text-tip
                  :tips="[
                    '数据匹配起始行是告知系统从第几行开始匹配数据导入，一般为第二行。',
                    '部分银行表格的前几行也可能用于展示其他文本，此情况下就需要选择正确的数据匹配起始行。',
                  ]"
                  :showNo="true"
                  v-if="item.key == 'match_line'"
                />
              </div>
              <div
                class="required-tip"
                v-if="item.checked && item.showRequired"
              >
                必填项
              </div>
            </div>
          </div>
        </div>
        <a-row class="mt-20" justify="center">
          <a-button type="primary" @click="onSubmit" :loading="submitLoading"
            >生成模板配置</a-button
          >
        </a-row>
      </template>
    </div>

    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="onClose">取消</a-button>
      <a-button
        type="primary"
        @click.prevent="editTemplate"
        style="margin-left: 10px"
        v-if="showTemplateList"
      >
        新增模板
      </a-button>
      <a-button
        type="primary"
        @click.prevent="backTemplateList"
        style="margin-left: 10px"
        v-else
      >
        返回
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  reactive,
  watch,
  toRefs,
  computed,
  toRaw,
  createVNode,
} from "vue";
import { Modal, Form, message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import moment from "moment";
import { useRoute, useRouter } from "vue-router";
import utils from "../../../../common/utils/utils";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { TextTip } from "bl-common-vue3";

export default defineComponent({
  name: "FlowTemplateModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: { TextTip },
  setup(props, context) {
    const router = useRouter();

    const title = computed(() => {
      if (state.showTemplateList) {
        return "线索模板管理";
      } else {
        if (state.editTemplateId) {
          return "编辑模板";
        } else {
          return "新增模板";
        }
      }
    });

    const state = reactive({
      templateList: [],
      columns: [
        {
          title: "模板名称",
          dataIndex: "name",
          key: "name",
          width: "20%",
          align: "center",
          ellipsis: true,
        },
        {
          title: "配置时间",
          dataIndex: "set_time",
          width: "20%",
          align: "center",
        },
        {
          title: "经办人",
          dataIndex: "cuser_uname",
          width: "20%",
          align: "center",
        },
        {
          title: "模板编号",
          dataIndex: "template_number",
          width: "20%",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "action",
          key: "action",
          width: "20%",
          align: "center",
        },
      ],
      showTemplateList: true,
      editTemplateId: 0,
      editTemplateName: "",
      editTemplateTable: [],
      lettersList: [],
      submitLoading: false,
    });

    const lettersList = computed(() => {
      let arr = [];
      for (let i = 0; i < 26; i++) {
        arr.push({
          label: String.fromCharCode(65 + i),
          value: String.fromCharCode(65 + i),
        });
      }
      return arr;
    });

    const rowList = computed(() => {
      let arr = [];
      for (let i = 0; i < 20; i++) {
        arr.push({
          label: i + 1,
          value: i + 1,
        });
      }
      return arr;
    });

    // 请求模板列表
    const getTemplateList = () => {
      request.get("/org", "/investmentTemplate/templateList").then((res) => {
        state.templateList = res.list;
      });
    };

    // 请求模板详情
    const getTemplateDetail = () => {
      request
        .get("/org", "/investmentTemplate/templateDetail", {
          id: state.editTemplateId,
        })
        .then((res) => {
          if (res.detail && res.detail.content) {
            res.detail.content.forEach((item) => {
              if (item.key == "voucher_no") {
                item.row = item.row.split("+");
              }
            });
            state.editTemplateTable = res.detail.content;
            state.editTemplateName = res.detail.name;
          }
        });
    };

    // 新增、编辑模板
    const editTemplate = (id) => {
      state.editTemplateName = "";
      if (id && id > 0) {
        state.editTemplateId = id;
        getTemplateDetail();
      } else {
        state.editTemplateId = 0;

        state.editTemplateTable = [
          {
            key: "contact_name",
            row: null,
            name: "姓名",
            checked: true,
          },
          { key: "contact_phone", row: null, name: "电话", checked: true },

          { key: "company", row: null, name: "公司", checked: false },
          { key: "village_name", row: null, name: "意向项目", checked: true },
          { key: "build_name", row: null, name: "意向楼宇", checked: true },
          {
            key: "expect_area_min",
            row: null,
            name: "需求面积段（最小）",
            checked: true,
          },
          {
            key: "expect_area_max",
            row: null,
            name: "需求面积段（最大）",
            checked: true,
          },
          { key: "remark", row: null, name: "备注", checked: false },
          {
            key: "match_line",
            row: null,
            name: "数据匹配起始行",
            checked: true,
          },
        ];
      }
      state.showTemplateList = false;
    };

    //删除模板
    const deleteTemplate = (id) => {
      if (id && id > 0) {
        Modal.confirm({
          title: () => "确定删除吗?",
          icon: () => createVNode(ExclamationCircleOutlined),
          centered: true,
          onOk() {
            request
              .del("/org", "/investmentTemplate/templateDel", { id })
              .then((res) => {
                message.success(res.msg || "删除成功");
                getTemplateList();
                context.emit("refresh");
              });
          },
        });
      }
    };

    const onSelectChange = (value) => {
      console.log(value);
    };

    const onClose = () => {
      context.emit("onClose");
    };

    const onSubmit = () => {
      state.submitLoading = true;
      message.destroy();
      if (!state.editTemplateName) {
        message.error("模板名称不能为空", 2);
        state.submitLoading = false;
        return;
      }
      let flag = false;
      state.editTemplateTable.forEach((item) => {
        if (item.checked && (!item.row || item.row.length == 0)) {
          item.showRequired = true;
          flag = true;
        } else {
          item.showRequired = false;
        }
      });
      if (flag) {
        message.error("请完善必填项", 2);
        state.submitLoading = false;
        return;
      }
      let content = JSON.parse(JSON.stringify(state.editTemplateTable));
      content.forEach((item) => {
        if (item.key == "voucher_no") {
          item.row = item.row.join("+");
        }
        delete item.showRequired;
      });
      let requestType = "post";
      let url = "/investmentTemplate/templateAdd";
      let submitParams = {
        name: state.editTemplateName,
        content: content,
        type: 1,
      };
      //   编辑
      if (state.editTemplateId) {
        requestType = "put";
        url = "/investmentTemplate/templateEdit";
        submitParams.id = state.editTemplateId;
      }
      request[requestType]("/org", url, { ...submitParams })
        .then((res) => {
          message.success(res.msg || "保存成功");
          state.submitLoading = false;
          getTemplateList();
          state.showTemplateList = true;
          context.emit("refresh");
        })
        .catch((err) => {
          state.submitLoading = false;
        });
    };

    const backTemplateList = () => {
      state.showTemplateList = true;
    };

    const init = () => {
      state.showTemplateList = true;
      state.submitLoading = false;
      getTemplateList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
          //新增模板
          // if (props.id == 0 || !props.id) {
          //   editTemplate();
          // }
          if (props.id) {
            if (props.id > 0) {
              editTemplate(props.id);
            } else {
              editTemplate();
            }
          }
        }
      }
    );

    return {
      ...toRefs(state),
      title,
      onClose,
      onSubmit,
      editTemplate,
      deleteTemplate,
      lettersList,
      rowList,
      onSelectChange,
      backTemplateList,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  height: 100%;
  overflow: hidden auto;

  :deep(.ant-table-thead) {
    font-size: 12px;
  }

  :deep(.ant-table-tbody) {
    font-size: 12px;
  }

  .edit-table {
    .edit-table-head {
      width: 100%;
      height: 55px;
      background-color: #fafafa;
      display: flex;
      align-items: center;
    }

    .edit-table-body {
      width: 100%;
      height: 520px;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
    }

    .edit-table-part {
      width: 100%; //一列
      // width: 50%;这是两列
      height: 55px;
      display: flex;
      position: relative;

      .edit-table-partChild {
        width: 30%;
        // width: 50%;//两列
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .edit-table-partCore {
          width: 70%;
          // width: 50%;//两列
          display: flex;
          align-items: center;
        }
      }

      .required-tip {
        color: red;
        position: absolute;
        left: 55%;
        bottom: -8px;
        font-size: 12px;
      }
    }

    .edit-table-part:nth-child(2n + 1) {
      padding-right: 1px;
    }

    .edit-table-part:nth-child(2n) {
      padding-left: 1px;
    }
  }
}
</style>
